import tiyData from "./list_data"
import ApiBase from "../../../../api/moudles/ApiBase";
import common_data from "./common_data";
import {isNotEmpty} from "../../../js/commonUtils";
import commonData from "./common_data";

/**展厅列表查询*/
export const queryStandsList = (self) => {
  let params = tiyData.tParam.searchParam;
  params.pageNum = tiyData.tPage.pageNum;
  params.pageSize = tiyData.tPage.pageSize;
  self.$Spin.show();
  self.$apiStand.queryStandsList(params).then(response => {
    tiyData.tData.standsList.splice(0);
    if(response.success) {
      let page = response.result;
      tiyData.tData.standsList.push(...page.list);
      tiyData.tPage.total = page.total;
    }else{
      tiyData.tPage.total = 0;
      self.$Message.error(response.errorMessage);
    }
    self.$Spin.hide();
  })
}

/**新增展厅时初始化参数*/
export const resetAddParam = (self) => {
  self.$refs.AStandAdd.$refs.standsBaseInfoForm.resetFields();
  tiyData.tParam.addParam.collectionHasDate = false;
  tiyData.tParam.addParam.collectionHasCategory = false;
  tiyData.tParam.addParam.collectionHasKeyword = false;
  tiyData.tParam.addParam.collectionPublishedStartDate = "";
  tiyData.tParam.addParam.collectionPublishedEndDate = "";
}

/**保存新增展厅
 * @param callback 回调函数
 * */
export const addStands = (self) => {
  self.$refs.AStandAdd.$refs.standsBaseInfoForm.validate(valid => {
    if(valid) {
      let params = tiyData.tParam.addParam;

      if(isNotEmpty(params.shortLink) && params.shortLink.indexOf("wholesale/")>=0) {
        self.$Modal.warning({title: '警告', content:'固定网址不能包含"wholesale/"!'});
        return;
      }

      if(params.collectionType!=commonData.collectionDic.categoryType&&params.collectionType!=commonData.collectionDic.customType&&params.hasProductArea && !params.collectionHasDate && !params.collectionHasKeyword && !params.collectionClassificationId) {
        self.$Modal.warning({title: "警告", content:"请至少填写一种条件！"});
        return;
      }
    //处理日期
      if(params.collectionPublishedStartDate && params.collectionPublishedStartDate instanceof Object){
        var localDate = params.collectionPublishedStartDate;
        params.collectionPublishedStartDate = new Date(Date.UTC(localDate.getFullYear(), localDate.getMonth(), localDate.getDate(),0,0,0)).toJSON();
      }
      if(params.collectionPublishedEndDate && params.collectionPublishedEndDate instanceof Object){
        var localDate = params.collectionPublishedEndDate;
        params.collectionPublishedEndDate = new Date(Date.UTC(localDate.getFullYear(), localDate.getMonth(), localDate.getDate(),0,0,0)).toJSON();
      }

      self.$Spin.show();
      self.$apiStand.saveStands(params).then(response => {
        if(response.success) {
          self.$Message.success("新增展厅保存成功！");
          afterSaveStands(self, response.result);
        }else{
          self.$Message.error(response.errorMessage);
        }
        self.$Spin.hide();
      });
    }else{
      console.error("validate failed")
    }
  });
}

export const addHtmlStands = (self) => {
  self.$refs.AStandAddHtml.$refs.standsBaseInfoForm.validate(valid => {
    if(valid) {
      let params = tiyData.tParam.addHtmlParam;
      if(isNotEmpty(params.shortLink) && params.shortLink.indexOf("wholesale/")>=0) {
        self.$Modal.warning({title: '警告', content:'固定网址不能包含"wholesale/"!'});
        return;
      }
      self.$Spin.show();
      self.$apiStand.saveHtmlStands(params).then(response => {
        self.$Spin.hide();
        if(response.success) {
          queryStandsList(self);
          tiyData.tStatus.modalAddHtml.isShow = false;
          self.$Message.success("新增展厅保存成功！");
          showModifyHtmlModal(response.result);
        }
      }).catch(() => {
        self.$Spin.hide();
        self.$Message.error("保存失败！");
      })
    }else{
      console.log("validate failed");
    }
  });
}

/**保存新增展厅成功之后*/
export const afterSaveStands = (self, standsId) => {
  queryStandsList(self);
  tiyData.tStatus.modalAdd.isShow = false;
  showModifyModal(standsId);
}

/**显示编辑展厅界面*/
export const showModifyModal = (standsId) => {
  tiyData.tParam.editParam.standsId = standsId;
  tiyData.tParam.editParam.modifyingTime = new Date().getTime();
  tiyData.tStatus.currentStep = 0;
  tiyData.tStatus.modalModify.isShow = true;
}

/**显示编辑html类型展厅的界面*/
export const showModifyHtmlModal = (standsId) => {
  tiyData.tParam.editHtmlParam.standsId = standsId;
  tiyData.tParam.editHtmlParam.modifyingTime = new Date().getTime();
  tiyData.tStatus.modalModifyHtml.isShow = true;
}

/**删除展厅
 * @param callback 回调函数
 * */
export const deleteStands = (self, standsId) => {
  let params = {id: standsId};
  self.$Spin.show();
  self.$apiStand.deleteStands(params).then(response => {
    if(response.success) {
      self.$Message.success("已经删除！");
      queryStandsList(self);
    }else{
      self.$Message.success(response.errorMessage);
    }
    self.$Spin.hide();
  });
}

export const beforePublishStands = (self, standId, callback) => {
  let params = {id: standId, state: common_data.standsDic.unPublishedState};
  self.$Spin.show();
  self.$apiStand.queryChildShowroomList(params).then(response => {
    self.$Spin.hide();
    if(response.result == null || response.result.length == 0) {//没有关联已发布展厅
      confirmPublishStands(self, standId, callback);
    }else{
      tiyData.tParam.childrenParam.showroomId = standId;
      tiyData.tParam.childrenParam.currentTime = new Date().getTime();

      tiyData.tStatus.modalChildren.type = 2;
      tiyData.tStatus.modalChildren.okText = "发布";
      tiyData.tStatus.modalChildren.isShow = true;
    }
  });
}

/**发布展厅
 * @param callback 回调函数
 * */
export const confirmPublishStands = (self, standId, callback) => {
  self.$Modal.confirm({
    title: "确认",
    content: "确定要发布此展厅吗？",
    okText: "发布",
    cancelText: "取消",
    onOk() {
      publishStands(self, standId, callback);
    }
  });
}

/**发布展厅
 * @param callback 回调函数
 * */
export const publishStands = (self, standId, callback) => {
  let params = {id: standId};
  self.$Spin.show();
  self.$apiStand.publishStands(params).then(response => {
    self.$Spin.hide();
    if(response.success) {
      self.$Message.success("已经发布！");
      if(callback) {
        callback(self);
      }
    }else{
      self.$Modal.error({title: "错误", content: response.errorMessage});
    }
  });
}

/**下线展厅
 * @param callback 回调函数
 * */
export const beforeOfflineStands = (self, standId, callback) => {
  let params = {id: standId, state: common_data.standsDic.publishedState};
  self.$Spin.show();
  self.$apiStand.queryParentShowroomList(params).then(response => {
    self.$Spin.hide();
    if(response.result == null || response.result.length == 0) {//没有关联已发布展厅
      confirmOfflineStands(self, standId, callback);
    }else{
      tiyData.tParam.parentsParam.showroomId = standId;
      tiyData.tParam.parentsParam.currentTime = new Date().getTime();
      tiyData.tStatus.modalParents.isShow = true;
    }
  });
}

export const confirmOfflineStands = (self, standId, callback) => {
  self.$Modal.confirm({
    title: "确认",
    content: "确定要将此展厅下线吗？",
    okText: "下线",
    cancelText: "取消",
    onOk() {
      offlineStands(self, standId, callback);
    }
  });
}

export const offlineStands = (self, standId, callback) => {
  let params = {id: standId};
  self.$Spin.show();
  self.$apiStand.offlineStands(params).then(response => {
    self.$Spin.hide();
    if(response.success) {
      self.$Message.success("已经下线！");
      if(callback) {
        callback(self);
      }
    }else{
      self.$Modal.error({title: "错误", content: response.errorMessage});
    }
  });
}

export const beforePreviewStands = (self, index) => {
  let stands = tiyData.tData.standsList[index];
  beforePreviewCheck(self, stands);
}

export const beforePreviewCheck = (self, stands) => {
  if(stands.type != 100 && !stands.shortLink){
    self.$Message.error("展厅没有固定网址，不能预览！");
    return;
  }
  let standsId=stands.id;
  let params = {id: standsId, state: common_data.standsDic.unPublishedState};
  self.$Spin.show();
  self.$apiStand.queryChildShowroomList(params).then(response => {
    self.$Spin.hide();
    if(response.result == null || response.result.length == 0) {//没有关联已发布展厅
      previewStandRoom(self, stands);
    }else{
      tiyData.tParam.childrenParam.showroomId = standsId;
      tiyData.tParam.childrenParam.index = index;
      tiyData.tParam.childrenParam.currentTime = new Date().getTime();

      tiyData.tStatus.modalChildren.type = 2;
      tiyData.tStatus.modalChildren.okText = "预览";
      tiyData.tStatus.modalChildren.isShow = true;
    }
  });
}

export const previewStands = (self, index) => {
  let stands = tiyData.tData.standsList[index];
  previewStandRoom(self, stands);
}

export const previewStandRoom = (self, stands) => {
  let type=stands.type;
  let standsId=stands.id;

  self.$Spin.show();
  let previewUrl = self.$store.getters.webDomain+"standInit/prepareStandRoom.do?code=li_6334522&type="+type+"&standRoomId="+standsId;
  self.$apiStand.previewStand(previewUrl,{}).then(response => {
    if(response.success) {
      self.$Message.success("生成页面成功！");
      // stands.pageCreated = true;
      // tiyData.tData.standsList.splice(index,1,stands);
      queryStandsList(self);
      window.open(self.$store.getters.webDomain+'tmp/'+response.result, "_blank")
    }else{
      self.$Message.success(response.errorMessage);
    }
    self.$Spin.hide();
  });
}

export const beforePublishPage = (self, index) => {
  let stands = tiyData.tData.standsList[index];
  beforePublishPageCheck(self, stands);
}

export const beforePublishPageCheck = (self, stands) => {
  if(stands.type != 100 && !stands.shortLink){
    self.$Message.error("展厅没有固定网址，不能发布！");
    return;
  }
  let standsId=stands.id;
  let params = {id: standsId, state: common_data.standsDic.unPublishedState};
  self.$Spin.show();
  self.$apiStand.queryChildShowroomList(params).then(response => {
    self.$Spin.hide();
    if(response.result == null || response.result.length == 0) {//没有关联已发布展厅
      publishStandRoomPage(self, stands);
    }else{
      tiyData.tParam.childrenParam.showroomId = standsId;
      tiyData.tParam.childrenParam.index = index;
      tiyData.tParam.childrenParam.currentTime = new Date().getTime();

      tiyData.tStatus.modalChildren.type = 3;
      tiyData.tStatus.modalChildren.okText = "发布";
      tiyData.tStatus.modalChildren.isShow = true;
    }
  });
}

export const publishPage = (self,index) => {
  let stands = tiyData.tData.standsList[index];
  publishStandRoomPage(self, stands);
}

export const publishStandRoomPage = (self, stands) => {
  let type = stands.type;
  let shortLink = "";
  if(type==100){
    shortLink = "index.html";
  }else{
    shortLink= encodeURIComponent(stands.shortLink);
  }
  self.$Spin.show();
  let publishPageUrl = self.$store.getters.webDomain+"standInit/publishStandRoom.do?code=li_6334522&fileName="+shortLink+"&standRoomId="+stands.id;

  ApiBase.send(publishPageUrl,{}).then(response => {
      if(response.success) {
        self.$Message.success("页面发布成功！");
        // stands.pageCreated = false;
        // tiyData.tData.standsList.splice(index,1,stands);
        queryStandsList(self);
      }else{
        let errorMsg = "页面发布失败！";
        if(response.errorMessage){
          errorMsg += response.errorMessage;
        }
        self.$Message.error(errorMsg);
      }
      self.$Spin.hide();
    }
  )
}

export const getReturnFilters = (self, returnFiltes) => {
  self.$apiStand.getReturnFilters().then(response => {
    returnFiltes.splice(0);
    if(response.success) {
      returnFiltes.push(...response.result);
    }else{
      console.error("查询屏蔽切面选项失败！"+response.errorMessage);
    }
  }).catch(() => {
    console.error("查询屏蔽切面选项失败！");
  })
}
